package com.haocang.szgm.ui.home.activity;

import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.haocang.commonlib.curve.BarChartManager;
import com.haocang.commonlib.loadingdialog.LoadingDialog;
import com.haocang.commonlib.network.interfaces.InitDataBeanBack;
import com.haocang.commonlib.network.interfaces.InitDataOneBeanBack;
import com.haocang.commonlib.pagegrid.PageGridView;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommFinalActivity;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.szgm.ui.floodpoint.activity.FloodPointDeatilActivity;
import com.haocang.szgm.ui.home.adapter.HomePageMenuAdapter;
import com.haocang.szgm.ui.home.adapter.RecycleGridDivider;
import com.haocang.szgm.ui.home.adapter.SwicthPumpStationAdapter;
import com.haocang.szgm.ui.home.bean.StationDataBean;
import com.haocang.szgm.ui.home.bean.SumWaterBean;
import com.haocang.szgm.ui.home.bean.SwicthPumpStationBean;
import com.haocang.szgm.ui.pipedata.bean.BillStatisticsBean;
import com.haocang.szgm.utils.config.WebApi;

import net.tsz.afinal.annotation.view.ViewInject;

import java.util.ArrayList;
import java.util.List;

public class HomeIndexChatActivity extends CommFinalActivity {


    @ViewInject(id = R.id.Bar_chat1)
    BarChart Bar_chat1;

    @ViewInject(id = R.id.pic_chart)
    PieChart pic_chart;

    @ViewInject(id = R.id.yes)
    TextView yes;
    @ViewInject(id = R.id.tv_title)
    TextView tv_title;
    @ViewInject(id = R.id.lin_lable)
    LinearLayout lin_lable;
    @ViewInject(id = R.id.ll_station)
    LinearLayout ll_station;
    @ViewInject(id = R.id.rv_station)
    RecyclerView rv_station;
    SwicthPumpStationAdapter mAdapter;

    Intent it;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        initEvent();

        initData();

    }


    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_home_index_chat;
    }

    @Override
    protected boolean showNavigation() {
        return false;
    }

    @Override
    protected int showMoreIcon() {
        return 0;
    }

    @Override
    protected String showTitleName() {
        return "关键指标";
    }


    private void initEvent() {
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });

    }

    private void initData() {

        it = getIntent();
        String ls_type = it.getStringExtra("TYPE");

        if (ls_type.equals("ZHIBIAO")) {
            tv_title.setText("水质净化厂");
            Bar_chat1.setVisibility(View.VISIBLE);
            pic_chart.setVisibility(View.GONE);
            lin_lable.setVisibility(View.VISIBLE);
            initSumWaterBean();
        } else if (ls_type.equals("SHIJIAN")) {
            tv_title.setText("事件统计");
            Bar_chat1.setVisibility(View.GONE);
            pic_chart.setVisibility(View.VISIBLE);
            lin_lable.setVisibility(View.GONE);
            initEventPie(
                    Integer.parseInt(it.getStringExtra("E1")),
                    Integer.parseInt(it.getStringExtra("E2")),
                    Integer.parseInt(it.getStringExtra("E3")));
        } else if (ls_type.equals("JSD")) {
            tv_title.setText("积水点统计");
            Bar_chat1.setVisibility(View.GONE);
            pic_chart.setVisibility(View.VISIBLE);
            lin_lable.setVisibility(View.GONE);
            initWaterPie(
                    Integer.parseInt(it.getStringExtra("W1"))
                    , Integer.parseInt(it.getStringExtra("W2"))
                    , Integer.parseInt(it.getStringExtra("W3"))
                    , Integer.parseInt(it.getStringExtra("W4"))
                    , Integer.parseInt(it.getStringExtra("W5")));
        } else if (ls_type.equals("BILL")) {
            tv_title.setText("今日工单统计");
            Bar_chat1.setVisibility(View.GONE);
            pic_chart.setVisibility(View.VISIBLE);
            lin_lable.setVisibility(View.GONE);
            initBillStatisticsPie();
        }else if (ls_type.equals("PUBPSTATION")){
            tv_title.setText("泵站状态");
            Bar_chat1.setVisibility(View.GONE);
            pic_chart.setVisibility(View.GONE);
            lin_lable.setVisibility(View.GONE);
            ll_station.setVisibility(View.VISIBLE);
            initStation();
        }
    }
    LoadingDialog dialog;
    private void initStation() {


        dialog = new LoadingDialog(HomeIndexChatActivity.this, "数据请求中");
        dialog.show();

        mAdapter = new SwicthPumpStationAdapter(HomeIndexChatActivity.this);

        rv_station.setLayoutManager((new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        }));
        rv_station.addItemDecoration(new RecycleGridDivider(this,1,false));
        rv_station.setAdapter(mAdapter);

        String url = WebApi.Api_GetPumbStatus;

        DataModel.GetApiRequestOneMode("SwicthPumpStationBean", url, new InitDataOneBeanBack<SwicthPumpStationBean>() {
            @Override
            public void callbak(boolean b, SwicthPumpStationBean data, String msg) {
                dialog.close();
                if (b){
                    List<StationDataBean> sdb = new ArrayList<>();
                    sdb.add(new StationDataBean(data.getBz1(),data.getBz1_hz()+"hz","泵站1"));
                    sdb.add(new StationDataBean(data.getBz2(),null,"泵站2"));
                    sdb.add(new StationDataBean(data.getBz3(),null,"泵站3"));
                    sdb.add(new StationDataBean(data.getBz4(),null,"泵站4"));
                    sdb.add(new StationDataBean(data.getBz5(),data.getBz2_hz()+"hz","泵站5"));
                    sdb.add(new StationDataBean(data.getBz6(),null,"泵站6"));
                    mAdapter.setNewData(sdb);
                }
            }
        });

    }



    private void initSumWaterBean() {

        DataModel.GetApiRequestMode("SumWaterBean", WebApi.Api_GetSumWater, new InitDataBeanBack<SumWaterBean>() {
            @Override
            public void callbak(boolean b, List<SumWaterBean> list, String msg) {
                if (b) {

                    if (list == null || list.size() == 0) {
                        ToastShow("无工单数据");
                        return;
                    }

                    List<Float> xAxisValues = new ArrayList<>();
                    List<List<Float>> yAxisValues = new ArrayList<>();
                    List<String> labels = new ArrayList<>();
                    List<Float> x1 = new ArrayList<>();
                    List<Float> x2 = new ArrayList<>();
                    List<Float> x3 = new ArrayList<>();
                    String[] xValues = new String[list.size()];

                    float index = 1.0f;
                    for (int i = 0; i < list.size(); i++) {
                        SumWaterBean model = list.get(i);
                        xAxisValues.add(index);
                        x1.add(Float.parseFloat(model.getZjs() == null ? "0" : model.getZjs()));
                        x2.add(Float.parseFloat(model.getZcs() == null ? "0" : model.getZcs()));
                        x3.add(Float.parseFloat(model.getShl() == null ? "0" : model.getShl()));
                        xValues[i] = model.getBbdate().substring(5);
                        index += 1.0f;
                    }

                    yAxisValues.add(x1);
                    yAxisValues.add(x2);
                    yAxisValues.add(x3);
                    labels.add("");
                    labels.add("");
                    labels.add("");
                    showBarChartMore(xAxisValues, yAxisValues, labels, xValues);
                } else {
                    ToastShow(msg);
                }

            }
        });

    }

    private void initEventPie(int a, int b, int c) {

        List<PieEntry> strings = new ArrayList<>();
        strings.add(new PieEntry(a, "未处理(" + a + ")"));
        strings.add(new PieEntry(b, "处理中(" + b + ")"));
        strings.add(new PieEntry(c, "已处理(" + c + ")"));

        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.red));
        colors.add(getResources().getColor(R.color.orange));
        colors.add(getResources().getColor(R.color.green));

        initPieChat(strings,colors,"【事件统计饼状图】");

        pic_chart.invalidate();

    }

    private void initBillStatisticsPie() {

        String ls_data = it.getStringExtra("Data");

        String[] arr = ls_data.split("\\/");

        int lf_OverCheckCount = Integer.parseInt(arr[0]);
        int AllCheckCount = Integer.parseInt(arr[1]);
        int lf_InCheckCount = AllCheckCount - lf_OverCheckCount;

        List<PieEntry> strings = new ArrayList<>();
        strings.add(new PieEntry(lf_InCheckCount, "处理中(" + lf_InCheckCount + ")"));
        strings.add(new PieEntry(lf_OverCheckCount, "已完成(" + lf_OverCheckCount + ")"));
        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.orange));
        colors.add(getResources().getColor(R.color.green));

        initPieChat(strings,colors,"【今日工单统计饼状图】");

        pic_chart.invalidate();
    }




    private void initWaterPie(int a, int b, int c, int d, int e) {

        List<PieEntry> strings = new ArrayList<>();
        strings.add(new PieEntry(a, "未处理(" + a + ")"));
        strings.add(new PieEntry(b, "处理中(" + b + ")"));
        strings.add(new PieEntry(c, "已处理(" + c + ")"));
        strings.add(new PieEntry(d, "未巡查(" + d + ")"));
        strings.add(new PieEntry(e, "未积水(" + e + ")"));

        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.red));
        colors.add(getResources().getColor(R.color.orange));
        colors.add(getResources().getColor(R.color.green));
        colors.add(getResources().getColor(R.color.blue));
        colors.add(getResources().getColor(R.color.gray));
        initPieChat(strings,colors,"【积水点统计饼状图】");
        pic_chart.invalidate();

    }


    /**===============================================
     * 创建时间：2019/10/21 14:05
     * 编 写 人：ShenC
     * 方法说明：设置饼图的样式
     *================================================
     * 修改内容：      修改时间：      修改人：
     *===============================================*/
    private void initPieChat(List<PieEntry> strings,ArrayList<Integer> colors,String ls_description){

        PieDataSet dataset = new PieDataSet(strings, "");

        dataset.setColors(colors);
        dataset.setDrawValues(true); //是否在图上显示数值
        dataset.setValueTextSize(14);//        文字的大小
        dataset.setValueTextColor(Color.RED);//        文字的颜色
        dataset.setValueTypeface(Typeface.DEFAULT_BOLD);//        文字的样式

        dataset.setValueLinePart1Length(0.4f);//      当值位置为外边线时，表示线的前半段长度。
        dataset.setValueLinePart2Length(0.4f);//      当值位置为外边线时，表示线的后半段长度。
        dataset.setValueLinePart1OffsetPercentage(80f);//      当ValuePosits为OutsiDice时，指示偏移为切片大小的百分比
        dataset.setValueLineColor(Color.parseColor("#a1a1a1"));// 当值位置为外边线时，表示线的颜色。
        dataset.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);//        设置Y值的位置是在圆内还是圆外
        dataset.setSliceSpace(0);//        设置每条之前的间隙
        dataset.setSelectionShift(5f); //设置饼状Item被选中时变化的距离

        //设置柱状上方数值的格式
        dataset.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value,Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                int n = (int) value;
                return n+"";
            }
        });

        PieData pieData = new PieData(dataset);
       // pieData.setValueFormatter(new PercentFormatter());
        pic_chart.setDrawEntryLabels(false);
        pic_chart.setData(pieData);
        Description description = new Description();//右下角说明
        description.setText(ls_description);
        pic_chart.setDescription(description);
        pic_chart.setExtraOffsets(15, 8, 55, 8);

        //获取图例
        Legend legend = pic_chart.getLegend();
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);  //设置图例水平显示
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); //顶部
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); //右对其
        legend.setXEntrySpace(7f);//x轴的间距
        legend.setYEntrySpace(10f); //y轴的间距
        legend.setYOffset(10f);  //图例的y偏移量
        legend.setXOffset(10f);  //图例x的偏移量
        legend.setTextColor(Color.parseColor("#000000")); //图例文字的颜色
        legend.setTextSize(13);  //图例文字的大小
    }



    private void showBarChartMore(List<Float> xAxisValues, List<List<Float>> yAxisValues, List<String> labels, String[] xValues) {
        BarChartManager barChartManager = new BarChartManager(Bar_chat1);
        List<Integer> colours = new ArrayList<>();
        colours.add(Color.parseColor("#ff953b"));
        colours.add(Color.parseColor("#00c2ae"));
        colours.add(Color.parseColor("#00a2ee"));
        barChartManager.showMoreBarChart(xAxisValues, yAxisValues, labels, colours, xValues);
        barChartManager.setXAxis(xValues.length, 0, 10);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            return super.onKeyDown(keyCode, event);
        } else {
            return false;
        }
    }

}
